package com.xk857.service.impl;

import com.xk857.domain.Log;
import com.xk857.repository.LogRepository;
import com.xk857.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.List;


@Service
public class LogServiceImpl implements LogService {

    @Autowired
    private LogRepository logRepository;


    @Override
    public List<Log> queryAll() {
        return logRepository.findAll();
    }

    /**
     * 保存日志数据
     * @param joinPoint /
     * @param log 日志实体
     */
    @Override
    public void save(ProceedingJoinPoint joinPoint, Log log) {
        log.setUsername("游客");//设置用户名，后面涉及到登陆后可根据实际情况修改
        log.setDescription(getDescription(joinPoint));//设置描述信息
        log.setMethod(getMethod(joinPoint));//设置方法名
        logRepository.save(log);
    }

    @Override
    public Object findByErrDetail(Long id) {
        return null;
    }

    /**
     * 获取描述信息
     * @return 返回方法信息，也就是@Log中的内容
     */
    public String getDescription(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        com.xk857.annotation.Log aopLog = method.getAnnotation(com.xk857.annotation.Log.class);
        return aopLog.value();
    }

    /**
     * 获取方法名
     * @return 返回执行方法名，也就是调用的是哪一个方法
     */
    public String getMethod(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        return  joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
    }

}
